package com.example.star.view.setting;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

import com.bumptech.glide.Glide;
import com.example.star.R;
import com.example.star.api_service.ApiUser;
import com.example.star.entity.User;
import com.example.star.retrofit.ApiClient;
import com.example.star.utils.ImageZoomDialogFragment;
import com.example.star.view.activity.PerimeterDetailActivity;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PersonalActivity extends AppCompatActivity {
    private String username;
    private ImageView loginAvatar;
    private EditText usernameEditText;
    private EditText passwordEditText;
    private EditText nicknameEditText;
    private EditText roleEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal);

        loginAvatar = findViewById(R.id.login_avatar);
        usernameEditText = findViewById(R.id.username_edit_text);
        passwordEditText = findViewById(R.id.password_edit_text);
        nicknameEditText = findViewById(R.id.nickname_edit_text);
        roleEditText = findViewById(R.id.role_edit_text);

        // 禁止修改用户名
        usernameEditText.setEnabled(false);
        passwordEditText.setEnabled(false);
        roleEditText.setEnabled(false);

        // 设置保存按钮点击事件
        Button btnSave = findViewById(R.id.save_button);
        btnSave.setOnClickListener(v -> saveUserInfo());

        // 加载用户信息
        SharedPreferences prefs = getSharedPreferences("user_info", MODE_PRIVATE);
        username = prefs.getString("username", "");
        getAndDisplayUserInfo(username);
    }

    private void getAndDisplayUserInfo(String username) {
        ApiUser apiUser = ApiClient.getApiUser();
        apiUser.getUserByUsername(username).enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.isSuccessful() && response.body() != null) {
                    User user = response.body();

                    //获取图片
                    Glide.with(PersonalActivity.this)
                            .load(user.getAvatar())
                            .placeholder(R.drawable.register)
                            .error(R.drawable.register)
                            .into(loginAvatar);

                    usernameEditText.setText(user.getUsername());
                    passwordEditText.setText(user.getPassword());
                    nicknameEditText.setText(user.getNickname());
                    roleEditText.setText(user.getRole());

                    // 设置头像点击监听器
                    loginAvatar.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String imageUrl = user.getAvatar();
                            ImageZoomDialogFragment dialogFragment = ImageZoomDialogFragment.newInstance(imageUrl);
                            FragmentManager fragmentManager = getSupportFragmentManager();
                            dialogFragment.show(fragmentManager, "image_zoom_dialog");
                        }
                    });
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                Toast.makeText(PersonalActivity.this, "加载信息失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void saveUserInfo() {
        String newPassword = passwordEditText.getText().toString().trim();
        String newNickname = nicknameEditText.getText().toString().trim();


        if (newPassword.isEmpty() || newNickname.isEmpty()) {
            Toast.makeText(this, "请填写所有字段", Toast.LENGTH_SHORT).show();
            return;
        }

        ApiUser apiUser = ApiClient.getApiUser();
        apiUser.updateUserByUsername(username, newPassword, newNickname)
                .enqueue(new Callback<User>() {
                    @Override
                    public void onResponse(Call<User> call, Response<User> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            updateLocalUserInfo(response.body());
                            Toast.makeText(PersonalActivity.this, "更改成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(PersonalActivity.this, "更改失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<User> call, Throwable t) {
                        Toast.makeText(PersonalActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void updateLocalUserInfo(User user) {
        SharedPreferences.Editor editor = getSharedPreferences("user_info", MODE_PRIVATE).edit();
        editor.putString("nickname", user.getNickname());
        editor.apply();
    }
}